package com.shiwaixiangcun.customer.module.intelligent

import android.content.Context
import android.os.Bundle
import android.os.Vibrator
import android.support.v7.app.AlertDialog
import cn.bingoogolapple.qrcode.core.QRCodeView
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.CameraIsBind
import com.shiwaixiangcun.customer.entity.CameraQRCode
import com.shiwaixiangcun.customer.entity.DeviceBaseEntity
import com.shiwaixiangcun.customer.network.ResponseConfig.SUCCESS
import com.shiwaixiangcun.customer.network.ResponseConfig.TOKEN_INVALID
import com.shiwaixiangcun.customer.network.StringDialogCallBack
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil.fromJson
import com.shiwaixiangcun.customer.utils.RefreshTokenUtil
import kotlinx.android.synthetic.main.activity_add_smart_camera.*
import kotlinx.android.synthetic.main.top_bar_white.*

/**
 * 添加智能摄像头
 *
 * 扫描二维码
 */
class AddSmartCameraActivity : BaseActivity(), QRCodeView.Delegate {
    var strToken: String? = null
    var refreshToken: String? = null
    val bundle = Bundle()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_smart_camera)
        initView()
        initData()
    }

    private fun initView() {
        strToken = AppSharePreferenceMgr.get(this, ConfigSps.CURRENT_TOKEN, "") as String
        refreshToken = AppSharePreferenceMgr.get(this, ConfigSps.CURRENT_REFRESH_TOKEN, "") as String
        tv_page_name.text = "添加智能摄像机"
        back_left.setOnClickListener { finish() }
        qrcode_view.setDelegate(this)


    }

    private fun initData() {
        qrcode_view.startCamera()
        qrcode_view.startSpotAndShowRect()
        qrcode_view.changeToScanQRCodeStyle()

    }

    override fun onRestart() {
        super.onRestart()
        initData()
    }


    override fun onStop() {
        qrcode_view.stopCamera()
        super.onStop()

    }

    override fun onDestroy() {
        qrcode_view.onDestroy()
        super.onDestroy()
    }


    /**
     * 显示对话框
     *
     * @param content 对话框提示内容
     */

    private fun showDialog(content: String) {
        val builder = AlertDialog.Builder(mContext)
        builder.setMessage(content)

        builder.setPositiveButton("扫描其他设备") { _, _ ->
            qrcode_view.startCamera()
            qrcode_view.showScanRect()
            qrcode_view.startSpot()
        }
        val dialog = builder.create()
        dialog.show()

    }


    override fun onScanQRCodeSuccess(result: String?) {
        vibrate()

        if (result == null) {
            return
        }

        val fromJson = fromJson<CameraQRCode>(result, CameraQRCode::class.java)


        bundle.putString("device_id", fromJson.SN)
        bundle.putString("device_name", fromJson.DT)
        bundle.putString("device_rc", fromJson.RC)
        vibrate()
        qrcode_view.stopSpot()
        checkDeviceBindOrNot(fromJson.SN)


    }

    /**
     * 验证设备是否被绑定
     */
    private fun checkDeviceBindOrNot(sn: String) {
        OkGo.get<String>(GlobalApi.checkDeviceIsBind)
                .params("deviceId", sn)
                .params("access_token", strToken)
                .execute(object : StringDialogCallBack(this) {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<DeviceBaseEntity<CameraIsBind>>() {}.type
                        val fromJson = fromJson<DeviceBaseEntity<CameraIsBind>>(response?.body(), type)
                        when (fromJson.responseCode) {
                            SUCCESS -> {
                                if (!fromJson.data.verificationCamera) {
                                    showDialog("该智能设备已经被其他用户绑定！")
                                } else {
                                    readyGoThenKill(ScanCameraSuccessActivity::class.java, bundle)
                                }

                            }
                            TOKEN_INVALID -> {
                                showToastShort("当前登录失效")
                                RefreshTokenUtil.refreshToken(mContext, refreshToken)
                            }
                        }


                    }

                })


    }

    private fun vibrate() {
        val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(200)
    }

    override fun onScanQRCodeOpenCameraError() {

    }
}
